package cx.mybatis.bingding;

import cx.mybatis.session.SqlSession;

import java.lang.reflect.Proxy;

/**
 * Mapper代理类的创建工厂
 * 提供对外统一的代理类获取接口
 * @Author:cxy
 * @Date:2022/4/9 9:41
 */
public class MapperProxyFactory<T> {

    private final Class<T> mapperInterface;

    public MapperProxyFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    public T newInstance(SqlSession sqlSession){
        MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface);
        return getInstance(mapperProxy);
    }

    @SuppressWarnings("unchecked")
    private T getInstance(MapperProxy<T> mapperProxy) {
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(),new Class[]{mapperInterface},mapperProxy);
    }

}
